package cc.site.security.filter;

import cc.site.common.exception.FineException;
import cc.site.common.utils.JwtUtils;
import cc.site.common.utils.TokenBody;
import cc.site.config.redis.utils.RedisCache;
import cc.site.security.bean.LoginUser;
import com.mysql.cj.util.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException {
        String token = req.getHeader("token");
        if (StringUtils.isNullOrEmpty(token)) {
            filterChain.doFilter(req, res);
            return;
        }

        // token 存在，读取用户id
        Claims claims = null;
        String userId;
//        try {
//            claims = JwtUtils.parseJWT(token);
//            userId = claims.getSubject();
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }

        try {
            TokenBody body = JwtUtils.getBodyByJwtToken(token);
            userId = body.getUserId();
        } catch (Exception e) {
            throw new FineException(HttpStatus.UNAUTHORIZED.value(), "JwtAuthTokenFilter jwt空指针异常");
        }

        // 从redis中获取用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (loginUser == null) {
            throw new FineException(HttpStatus.UNAUTHORIZED.value(), "token非法");
        }

        // 认证信息存入SecurityContextHolder
        UsernamePasswordAuthenticationToken t = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(t);

        filterChain.doFilter(req, res);
    }

}
